package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.contant.Contants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * rpc 客户端
 * 1.发送请求
 * 2.接受响应
 */
public class RpcClient {
    public static void main(String[] args) throws Exception{
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Contants.HOST);
        connectionFactory.setPort(Contants.PORT);
        connectionFactory.setUsername(Contants.USER_NAME);
        connectionFactory.setPassword(Contants.PASSWORD);
        connectionFactory.setVirtualHost(Contants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2.开启信道
        Channel channel = connection.createChannel();
        channel.queueDeclare(Contants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Contants.RPC_RESPONSE_QUEUE,true,false,false,null);
        // 3.发送请求
        // 设置请求的相关属性
        String msg = "hello rpc";
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .correlationId(correlationId) // 设置请求的唯一标识
                .replyTo(Contants.RPC_RESPONSE_QUEUE) // 告诉服务端(Server)完成响应后将结果放在 Contants.RPC_RESPONSE_QUEUE 中
                .build();
        channel.basicPublish("",Contants.RPC_REQUEST_QUEUE,props,msg.getBytes());

        // 4.接受响应
        // 使用阻塞队列,存储响应信息
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg = new String(body);
                System.out.println("接收到回调消息: " + respMsg);
                if (correlationId.equals(properties.getCorrelationId())){
                    // 如果correlationId一致,校验成功
                    response.offer(respMsg);
                }
            }
        };
        channel.basicConsume(Contants.RPC_RESPONSE_QUEUE,true,consumer); // 客户端的消费队列是 Contants.RPC_RESPONSE_QUEUE
        String result = response.take();
        System.out.println("RPC Client 响应结果: "+result);

    }
}
